$(function() {
	let doNum = 0
	start()

	function start() {
		let isLogin = getCookie("bili_jct")
		if (!isLogin) {
			// 没有登陆退出
			console.log("没有登陆账户，退出执行")
			sendMsgToBackground("not_login")
			return
		}else{
			sendMsgToBackground("has_login")
		}

		let lastDoTimeTxt = getCookie("bilibili_exp_time")
		if (!lastDoTimeTxt) {
			requestGetRewardInfo()
		} else {
			let lastTimeArr = lastDoTimeTxt.split("/")
			let todayTimeArr = new Date().toLocaleDateString().split("/")
			let hasDid = todayTimeArr.every((value, index) => {
				if (parseInt(value) > parseInt(lastTimeArr[index])) {
					requestGetRewardInfo()
					return false
				}
				return true
			})
			if(hasDid){
				sendMsgToBackground("today_did")
			}else{
				sendMsgToBackground("start_do")
			}
		}
	}

	// 检查是否还能获取经验
	function requestGetRewardInfo() {
		// console.log("requestGetAwardInfo")
		console.log("执行次数：", ++doNum)
		if (doNum > 5) {
			//防止出错 退出
			sendMsgToBackground("did_unexcept")
			return
		}

		let url = "https://account.bilibili.com/home/reward"

		$.ajax({
			type: 'GET',
			url: url,
			success: res => {
				// console.log("回调结果succ", res)
				if (res.code == 0) {
					let avExp = res.data.coins_av
					if (avExp < 50) {
						requestGetUserInfo()
					} else {
						let today = new Date()
						let todayTxt = today.toLocaleDateString()
						setCookie("bilibili_exp_time", todayTxt)
					}
				}else{
					console.info("回调结果fail", res)
					sendMsgToBackground("response_unexcept")
				}
			},
			error: err => {
				console.error("回调结果fail", res)
				sendMsgToBackground("response_err")
			}
		})
	}

	// 检查剩余硬币
	function requestGetUserInfo() {
		// console.log("requestGetUserInfo")
		let url = "https://account.bilibili.com/home/userInfo"

		$.ajax({
			type: 'GET',
			url: url,
			success: res => {
				// console.log("回调结果succ", res)
				if (res.code == 0) {
					let coins = res.data.coins
					if (coins > 0) {
						requestUseConin()
					} else {
						let today = new Date()
						let todayTxt = today.toLocaleDateString()
						setCookie("bilibili_exp_time", todayTxt)
					}
				}else{
					console.info("回调结果fail", res)
					sendMsgToBackground("response_unexcept")
				}
			},
			error: err => {
				console.error("回调结果fail", res)
				sendMsgToBackground("response_err")
			}
		})
	}

	// 记录投币失败的次数
	let useConinFail = 0

	// 投币
	function requestUseConin() {
		// console.log("requestUseConin")
		let lastAid = getCookie("lastAid")
		if (!lastAid) {
			lastAid = 1
		} else {
			lastAid = parseInt(lastAid)
		}

		// 随机增加
		for (let i = Math.pow(2, useConinFail); i > 0; i--) {
			let randomNum = Math.ceil(Math.random() * 10)
			lastAid += randomNum
		}

		setCookie("lastAid", lastAid)

		let url = "https://api.bilibili.com/x/web-interface/coin/add"
		let aid
		let data = {
			aid: lastAid, //视频id
			multiply: 1, //硬币数
			cross_domain: true,
			csrf: getCookie("bili_jct") //账号cookie
		}

		$.ajax({
			type: 'POST',
			url: url,
			data: data,
			success: res => {
				// console.log("回调结果succ", res)
				if (res.code == 0) {
					useConinFail = 0
					requestGetRewardInfo()
				} else {
					// 异常处理
					useConinFail++
					requestUseConin()
					console.log("投币失败", res.message)
				}
			},
			error: err => {
				console.error("回调结果fail", res)
				sendMsgToBackground("response_err")
			}
		})
	}

	//写cookies 
	function setCookie(name, value) {
		let Days = 30;
		let exp = new Date();
		exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
		document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
	}

	//读取cookies 
	function getCookie(name) {
		let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

		if (arr = document.cookie.match(reg))

			return unescape(arr[2]);
		else
			return null;
	}

	$('body').click(() => {
		sendMsgToBackground("来自前台页面的主动调用")
	})
	// 给插件发消息
	function sendMsgToBackground(msg) {
		chrome.extension.sendMessage({
			cmd: msg
		}, function(response) {
			console.log(response);
		});
	}
})